package com.chw.admin.permission;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageInfo;
import com.chw.admin.permission.PermissionSecurity.PermissionModule;
import com.chw.admin.permission.groupPermission.GroupPermission;
import com.chw.admin.permission.groupPermission.GroupPermissionMapper;
import com.chw.admin.permission.rolePermission.RolePermission;
import com.chw.admin.permission.rolePermission.RolePermissionMapper;
import com.chw.admin.permission.userPermission.UserPermission;
import com.chw.admin.permission.userPermission.UserPermissionMapper;
import com.chw.constants.Constants;
import com.chw.utils.CommonFieldsUtil;
import com.chw.utils.GsonUtils;
import com.chw.utils.LogUtil;

@Service
public class SysPermissionService implements ISysPermissionService {
	
	private static LogUtil log = LogUtil.newInstance(SysPermissionService.class);
	
	@Autowired
	private SysPermissionMapper sysPermissionMapper;
	
	@Autowired
	private ModulePermissionMapper modulePermissionMapper;
	
	@Autowired
	private UserPermissionMapper userPermissionMapper;
	
	@Autowired
	private RolePermissionMapper rolePermissionMapper;
	
	@Autowired
	private GroupPermissionMapper groupPermissionMapper;

	public List<PermissionSecurity> getPermissionSecuritys() throws Exception{
		//读取权限功能模块
		Resource resource = new ClassPathResource("permission.json");
		if(resource!=null)
		{
			File file = resource.getFile();
			if(file.exists())
			{
				String permissionSecuritys = FileUtils.readFileToString(file);
				log.debug(permissionSecuritys);
				return GsonUtils.fromGsonList(permissionSecuritys, PermissionSecurity.class);
			}
		}
		return null;
	}
	
	
	@Override
	public PageInfo<Map<String,Object>> pageModule(String record, Integer currentPage, Integer pageSize)
			throws Exception {
		PageInfo<Map<String, Object>> page = new PageInfo<Map<String,Object>>();

		//读取权限功能模块
		List<PermissionSecurity> permissions = getPermissionSecuritys();
		if(permissions!=null && !permissions.isEmpty())
		{
			String moduleName = record;
			
			//模糊查询
			List<PermissionSecurity> lists = null;
			if(StringUtils.isNotBlank(moduleName))
			{
				lists = new ArrayList<PermissionSecurity>();
				for(PermissionSecurity permission : permissions)
				{
					String module = permission.getModule();
					if(StringUtils.isNotBlank(module) && module.indexOf(moduleName)>-1)
					{
						lists.add(permission);
					}
				}
			}else{
				lists = permissions;
			}
			
			//分页
			if(currentPage<1)
			{
				currentPage = 1;
			}
			
			int size = lists.size();
			int formIndex = (currentPage-1)*pageSize;
			int toIndex = currentPage*pageSize;
			
			if(size>formIndex)
			{
				if(size<toIndex)
				{
					lists = lists.subList(formIndex,lists.size());
				}else{
					lists = lists.subList(formIndex, toIndex);
				}
			}

			//拼装操作串
			List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
			
			Map<String,Object> map = null;
			
			for(PermissionSecurity permission : lists)
			{
				String module = permission.getModule();
				List<PermissionModule> list = permission.getPermissionModule();
				
				map = new HashMap<String,Object>();
				map.put("module", module);
				
				List<String> names = new ArrayList<String>();
				for(PermissionModule pm : list)
				{
					names.add(pm.getName());
				}
				map.put("opers", StringUtils.join(names, "|"));
				result.add(map);
			}
			
			page.setTotal(permissions.size());
			page.setList(result);
			page.setPageNum(currentPage);
			page.setPageSize(pageSize);
		}
		return page;
	}

	@Override
	public void deleteModule(ModulePermission record) throws Exception {
		//删除module模块
		CommonFieldsUtil.setUpdateValue(record);
		record.setEnabledFlag(Constants.ENABLED_FLAG_N);
		modulePermissionMapper.updateByIdSelective(record);
		//删除功能权限
		SysPermission permission = new SysPermission();
		permission.setCategory(Constants.PERMISSION_CATEGORY_FUNC);
		permission.setRelId(record.getId());
		List<SysPermission> funcs = sysPermissionMapper.find(permission);
		for(SysPermission pf : funcs){
			CommonFieldsUtil.setUpdateValue(pf);
			pf.setEnabledFlag(Constants.ENABLED_FLAG_N);
			sysPermissionMapper.updateByIdSelective(pf);
		}
	}

	@Override
	public List<Map<String, Object>> getMenuPermission(String id,String type) throws Exception {
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> parentMenus = null;
		Map<String,Object> record = new HashMap<String,Object>();
		//获取父菜单
		record.put("level", 1);
		if(Constants.PERMISSION_USER.equalsIgnoreCase(type))
		{
			record.put("userId", id);
			parentMenus = userPermissionMapper.findMenuPermissionMap(record);
		}else if(Constants.PERMISSION_GROUP.equalsIgnoreCase(type)){
			record.put("groupId", id);
			parentMenus = groupPermissionMapper.findMenuPermissionMap(record);
		}else if(Constants.PERMISSION_ROLE.equalsIgnoreCase(type)){
			record.put("roleId", id);
			parentMenus = rolePermissionMapper.findMenuPermissionMap(record);
		}

		if(parentMenus!=null && !parentMenus.isEmpty())
		{
			for(Map<String,Object> m : parentMenus){
				List<Map<String,Object>> children = new ArrayList<Map<String,Object>>();
				record.put("level", 2);
				record.put("parentId", m.get("menuId"));
				List<Map<String,Object>> childrenMenus = null;
				
				if(Constants.PERMISSION_USER.equalsIgnoreCase(type))
				{
					childrenMenus = userPermissionMapper.findMenuPermissionMap(record);
				}else if(Constants.PERMISSION_GROUP.equalsIgnoreCase(type)){
					childrenMenus = groupPermissionMapper.findMenuPermissionMap(record);
				}else if(Constants.PERMISSION_ROLE.equalsIgnoreCase(type)){
					childrenMenus = rolePermissionMapper.findMenuPermissionMap(record);
				}
				
				if(childrenMenus!=null && !childrenMenus.isEmpty())
				{
					for(Map<String,Object> c : childrenMenus){
						children.add(c);
					}
					m.put("children", children);
				}
				result.add(m);
			}
		}
		return result;
	}

	@Override
	public List<Map<String, Object>> getFuncPermission(String id,String type) throws Exception {
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		Map<String,Object> map = null;
		//扫描所有功能模块
		List<PermissionSecurity> permissions = getPermissionSecuritys();
		if(permissions!=null && !permissions.isEmpty())
		{
			//过滤用户或者用户组、角色的权限
			for(PermissionSecurity permission : permissions){
				map = new HashMap<String,Object>();
				map.put("name", permission.getModule());
				List<PermissionModule> permissionModules = permission.getPermissionModule();
				
				List<Map<String,Object>> children = new ArrayList<Map<String,Object>>();
				
				for(PermissionModule permissionModule : permissionModules){
					Map<String,Object> cmap = new HashMap<String,Object>();
					cmap.put("name", permissionModule.getName());
					String permissionid = permissionModule.getPermissionid();
					cmap.put("permissionid",permissionid);
					cmap.put("checked", hasPermissionByUser(id,type,permissionid));
					children.add(cmap);
				}
				map.put("children", children);
				result.add(map);
			}
		}
		return result;
	}

	public int hasPermissionByUser(String id,String type,String permissionid){
		@SuppressWarnings("rawtypes")
		List lists = getFuncPermissionByUser(id,type);
		
		int checked = 0;
		if(lists!=null && !lists.isEmpty())
		{
			for(int i=0;i<lists.size();i++)
			{
				Object obj = lists.get(i);
				if(obj instanceof UserPermission && permissionid.equals(((UserPermission) obj).getPermissionId()))
				{
					checked = 1;
					break;
				}else if(obj instanceof GroupPermission && permissionid.equals(((GroupPermission)obj).getPermissionId())){
					checked = 1;
					break;
				}else if(obj instanceof RolePermission && permissionid.equals(((RolePermission) obj).getPermissionId())){
					checked = 1;
					break;
				}
			}
		}
		return checked;
	}
	
	//查询用户或者用户组、角色的权限
	@SuppressWarnings("rawtypes")
	public List getFuncPermissionByUser(String id,String type){
		if(Constants.PERMISSION_USER.equalsIgnoreCase(type))
		{
			UserPermission record = new UserPermission();
			record.setUserId(id);
			record.setEnabledFlag(Constants.ENABLED_FLAG_Y);
			return userPermissionMapper.find(record);
		}else if(Constants.PERMISSION_GROUP.equalsIgnoreCase(type)){
			GroupPermission record = new GroupPermission();
			record.setGroupId(id);
			record.setEnabledFlag(Constants.ENABLED_FLAG_Y);
			return groupPermissionMapper.find(record);
		}else if(Constants.PERMISSION_ROLE.equalsIgnoreCase(type)){
			RolePermission record = new RolePermission();
			record.setRoleId(id);
			record.setEnabledFlag(Constants.ENABLED_FLAG_Y);
			return rolePermissionMapper.find(record);
		}
		return null;
	}

	@Override
	public void saveOrUpdatePermission(String id,String type,String permissionid,String flag) throws Exception {
		//根据id、permissionid查询是否存在
		if(Constants.PERMISSION_USER.equalsIgnoreCase(type)){
			UserPermission record = new UserPermission();
			record.setUserId(id);
			record.setPermissionId(permissionid);
			List<UserPermission> list = userPermissionMapper.find(record);
			if(list!=null && !list.isEmpty())
			{
				record = list.get(0);
				//存在更新状态
				CommonFieldsUtil.setUpdateValue(record);
				record.setEnabledFlag(flag);
				userPermissionMapper.updateByIdSelective(record);
			}else{
				//新增
				CommonFieldsUtil.setCreateValue(record);
				userPermissionMapper.insert(record);
			}
		}else if(Constants.PERMISSION_GROUP.equalsIgnoreCase(type)){
			GroupPermission record = new GroupPermission();
			record.setGroupId(id);
			record.setPermissionId(permissionid);
			List<GroupPermission> list = groupPermissionMapper.find(record);
			if(list!=null && !list.isEmpty())
			{
				record = list.get(0);
				//存在更新状态
				CommonFieldsUtil.setUpdateValue(record);
				record.setEnabledFlag(flag);
				groupPermissionMapper.updateByIdSelective(record);
			}else{
				//新增
				CommonFieldsUtil.setCreateValue(record);
				groupPermissionMapper.insert(record);
			}
		}else if(Constants.PERMISSION_ROLE.equalsIgnoreCase(type)){
			RolePermission record = new RolePermission();
			record.setRoleId(id);
			record.setPermissionId(permissionid);
			List<RolePermission> list = rolePermissionMapper.find(record);
			if(list!=null && !list.isEmpty())
			{
				record = list.get(0);
				//存在更新状态
				CommonFieldsUtil.setUpdateValue(record);
				record.setEnabledFlag(flag);
				rolePermissionMapper.updateByIdSelective(record);
			}else{
				//新增
				CommonFieldsUtil.setCreateValue(record);
				rolePermissionMapper.insert(record);
			}
		}
	}

	@Override
	public List<Map<String,Object>> findModulePermissionByUser() throws Exception {
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		//扫描所有功能模块
		List<PermissionSecurity> permissions = getPermissionSecuritys();
		if(permissions!=null && !permissions.isEmpty())
		{
			Map<String,Object> map = new HashMap<String,Object>();
			String userid = CommonFieldsUtil.getCurrentUserId();
			map.put("userId", userid);
			List<Map<String,Object>> lists = sysPermissionMapper.findByUser(map);
			
			Map<String,Object> rmap = null;
			for(Map<String,Object> list : lists){
				for(PermissionSecurity permission : permissions){
					List<PermissionModule> permissionModules = permission.getPermissionModule();
					for(PermissionModule permissionModule : permissionModules){
						String permissionid = permissionModule.getPermissionid();
						if(permissionid.equals(list.get("permissionid")))
						{
							rmap = new HashMap<String,Object>();
							String btn_func = permissionModule.getBtnfunc();
							if(StringUtils.isNotBlank(btn_func))
							{
								rmap.put("btn_func", btn_func);
								result.add(rmap);
							}
							break;
						}
					}
				}
			}
		}
		return result;
	}
}
